<?php

namespace app\communal\controller;

vendor('aliyun-oss-php-sdk-master.autoload');

use OSS\OssClient;
use OSS\Core\OssException;

class UploadImg
{
    private $obj_model_name;

    private $str_model_name;

    private $str_id_name;

    private $arr_type = [];

    public function __construct($str_model_name)
    {
        $this->str_model_name = $str_model_name;
        switch ($str_model_name) {
            case 'user': // 用户端
                $this->obj_model_name = \app\model\UserInfo::getInstance();
                $this->str_id_name = 'user_id';
                $this->arr_type = ['id_card']; // id_card-身份证
                break;
            default:
                return false;
        }
    }

    /**
     * 上传图片
     * @param string $str_module_name 模块名称 user-用户端、courier-快递端
     * @param string $str_type 图片分类 goods、category、ad、county、head_img
     * @note 图片格式 'jpg', 'jpeg', 'gif', 'png'
     */
    public function uploadImg($str_type)
    {
        _toCompare(in_array($str_type, $this->arr_type), '===', false, 10818); // 图片分类不正确

        _toCompare(!isset($_FILES['file_data']['name']), '===', true, 13018);
        _toCompare(!isset($_FILES['file_data']['type']), '===', true, 13018);
        _toCompare(!isset($_FILES['file_data']['tmp_name']), '===', true, 13018);
        _toCompare(!isset($_FILES['file_data']['error']), '===', true, 13018);

        $arr_file = $_FILES['file_data'];

        // 文件名称
        $str_name = $arr_file['name'];
        // 得到文件类型，并且都转化成小写
        $str_type = strtolower(substr($str_name, strrpos($str_name, '.') + 1));
        // 定义允许上传的类型
        $arr_allow_type = array('jpg', 'jpeg', 'gif', 'png');
        // 判断文件类型是否被允许上传
        _toCompare(!in_array($str_type, $arr_allow_type), '===', true, 12085);

        // 判断是否是通过HTTP POST上传的 必须是通过HTTP POST上传的
        _toCompare(!is_uploaded_file($arr_file['tmp_name']), '===', true, 12086);

        // 新的图片名称
        $str_new_name = date('YmdHis') . rand(100000, 999999);

        $object = config('oss.oss_object') . $str_type . DS . $str_new_name;

        try {
            $ossClient = new OssClient(config('oss.oss_access_key_id'), config('oss.oss_access_key_secret'), config('oss.oss_endpoint'));  //
            $ossClient->uploadFile(config('oss.oss_bucket'), $object, $arr_file['tmp_name']);
        } catch (OssException $e) {
            _returnError(12087);
        }

        $str_img_url = 'http://' . config('oss.oss_bucket') . '.' . config('oss.oss_endpoint') . '/' . $object;

        _returnData(['imgUrl' => $str_img_url]);
    }
}